//创建用户相关小仓库
import { defineStore } from 'pinia';
//引入接口
import { reqLogin, reqUserInfo, reqLogout } from '../../api/user'
//引入数据类型
import { loginFromData, loginResponseData, userInfoReponseData } from '@/api/user/type';
import type { UserState } from './types/types'
//引入操作本地存储方法
import { SET_TOKEN, REMOVE_TOKEN, } from '../../utils/token'
//引入路由(常量路由)
import { constantRouter, asnysRoute, anyRoute } from '@/router/routes'
import { ElNotification } from 'element-plus'
import { h } from 'vue'
import router from '@/router';
//由于cloneDeep是js文件，所以需忽略js校验
//@ts-ignore
//引入深拷贝的方法
import cloneDeep from 'lodash/cloneDeep'

//用于过滤当前要展示的异步路由
function filterAsyncRoute(asnysRoute: any, routes: any) {
  return asnysRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true
    }
  })
}

// 创建你的存储实例
let userStore = defineStore('User', {
  // 可选：你可以为存储提供一个ID
  state: (): UserState => {
    return {
      //直接从本地存储持久化
      token: localStorage.getItem('TOKEN'),
      menuRoutes: constantRouter,  //仓库存储生成菜单需要的数组(路由)
      username: '',
      avatar: '',
      //存储是否含有按钮的标识
      bottons:[],
    }
  },
  actions: {
    // 定义你的操作（actions）
    // 例如：
    //async会返回一个成功primase对象
    async userLogin(data: loginFromData) {
      let result: loginResponseData = await reqLogin(data)
      console.log(result)
      if (result.code === 200) {
        this.token = String(result.data)
        SET_TOKEN((result.data as string))
        return 'OK'
      } else {
        return Promise.reject(new Error(result.data))
      }
      //成功请求：成功200->token
      //登陆失败：失败201->失败消息
    },
    //获取用户信息的方法
    async userInfo() {
      //获取用户信息存储在仓库中
      let result: userInfoReponseData = await reqUserInfo();
      console.log(result)
      //如何获取用户信息成功，则存储
      if (result.code == 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        this.bottons = result.data.buttons
        //计算当前用户展示异步路由
        let userAsyncRoute =  filterAsyncRoute(cloneDeep(asnysRoute), result.data.routes)
        this.menuRoutes = [...constantRouter,...userAsyncRoute,...anyRoute];
        //目前路由器管理的只有常量路由：用户计算完毕的异步路由，以及任意路由动态追加
        [...userAsyncRoute,...anyRoute].forEach((route:any)=>{
          router.addRoute(route)
        })
        return 'OK'
      } else {
        return Promise.reject(new Error(result.message))
      }

    },
    //退出登录
    async userLogout() {
      let result: any = await reqLogout();
      console.log(result)
      if (result.code === 200) {
        this.token = ''
        this.avatar = ''
        this.username = ''
        REMOVE_TOKEN();
        setTimeout(() => {
          ElNotification({
            type: "error",
            title: '用户信息失效',
            message: h('i', { style: 'color: teal' }, 'Please log out of the system.'),
            duration: 1000
          })   
        }, 500);
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    }
  },
  getters: {
    // 定义你的获取器（getters）
    // 例如：

  }
});

//对外暴露
export default userStore;
